package com.ymdx.action;

import com.ymdx.util.tool.DateUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * Created by yangliwei on 2017/8/9.
 */
@Action(value = "/upload", params = {"maximumSize", "1000000"})
public class UploadAction extends GenericActionSupport {
    private File upload;
    //这两个的命名格式 前缀为文件名称 后缀为FileName,ContentType
    private String uploadFileName;//****.jpg
    private String uploadContentType;//image/jpg

    private long maximumSize = 1000000;
    private final String[] allowedTypes = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".sb2"};



    /**
     * 上传图片
     *
     * @return
     */
    @Action(value = "/image", results = {@Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data"
    })})
    public String image() {
//          权限控制
        Object userId = session.get("user");
        Object adminId = session.get("admin");
        if (userId == null && adminId ==null) {
            responseTool.setStatus(0);
            responseTool.setCode("user_no_login");
            return SUCCESS;
        }

        check();
        if (responseTool.getStatus() == 0) {
            responseTool.setStatus(0);
            responseTool.setCode("upload_content_type_error");
            return SUCCESS;
        }

        String realpath = ServletActionContext.getServletContext().getRealPath(File.separator);
        String filename = DateUtils.getDateString(new Date()) + UUID.randomUUID().toString().substring(0, 4) + uploadFileName.substring(uploadFileName.lastIndexOf("."));
        File saveFile = new File(realpath + File.separator + "upload" + File.separator + "images" + File.separator + filename);
        if (!saveFile.getParentFile().exists()) {
            if (!saveFile.getParentFile().mkdirs()) {
                responseTool.setStatus(0);
                responseTool.setCode("upload_fail");
                return SUCCESS;
            }
        }
        try {
            FileUtils.copyFile(upload, saveFile);
        } catch (IOException e) {
            responseTool.setStatus(0);
            responseTool.setCode("upload_fail");
            return SUCCESS;
        }

        String url = getUrlPre() + "upload/images/" + filename;
        responseTool.setStatus(1);
        responseTool.setData(url);
        return SUCCESS;
    }

    @Action(value = "/sb2", results = {@Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data"
    })})
    public String sb2() {
        Object userId = session.get("user");
        Object adminId = session.get("admin");
        if (userId == null && adminId == null) {
            responseTool.setStatus(0);
            responseTool.setCode("user_no_login");
            return SUCCESS;
        }
        check();
        if (responseTool.getStatus() == 0) {
            responseTool.setStatus(0);
            responseTool.setCode("upload_content_type_error");
            return SUCCESS;
        }

        String realpath = ServletActionContext.getServletContext().getRealPath(File.separator);
        String filename = DateUtils.getDateString(new Date()) + UUID.randomUUID().toString().substring(0, 4) + uploadFileName.substring(uploadFileName.lastIndexOf("."));
        File saveFile = new File(realpath + File.separator + "upload" + File.separator + "sb2" + File.separator + filename);
        if (!saveFile.getParentFile().exists()) {
            if (!saveFile.getParentFile().mkdirs()) {
                responseTool.setStatus(0);
                responseTool.setCode("upload_fail");
                return SUCCESS;
            }
        }
        try {
            FileUtils.copyFile(upload, saveFile);
        } catch (IOException e) {
            responseTool.setStatus(0);
            responseTool.setCode("upload_fail");
            return SUCCESS;
        }

//        String url = getUrlPre() + "upload/sb2/" + filename;
        //这里保存的是服务器地址 不用前缀
        String url = "/upload/sb2/" + filename;
        responseTool.setStatus(1);
        responseTool.setData(url);

        return SUCCESS;
    }

    private void check() {
        if (upload == null || StringUtils.isAnyBlank(uploadFileName, uploadContentType)) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return;
        }
        boolean flag = false;
        for (int i = 0; i < allowedTypes.length; i++) {
            if (uploadFileName.toLowerCase().endsWith(allowedTypes[i].toLowerCase())) {
                flag = true;
            }
        }
        if (upload.length() > maximumSize) {
            flag = false;
        }
        responseTool.setStatus(flag ? 1 : 0);

    }


    private String getUrlPre() {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/";
    }


    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public long getMaximumSize() {
        return maximumSize;
    }

    public void setMaximumSize(long maximumSize) {
        this.maximumSize = maximumSize;
    }


}
